package com.bkitclub.mobiledevcamp.horseword;

import java.util.Vector;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;

import com.bkitclub.mobiledevcamp.horseword.customGUI.BitmapFont;
import com.bkitclub.mobiledevcamp.horseword.customGUI.CustomButton;
import com.bkitclub.mobiledevcamp.horseword.util.Const;
import com.bkitclub.mobiledevcamp.horseword.util.ResourceManager;

public class PlayActivity extends Activity{
	private Handler handler;
	private ImageView[][] cells;
	private static final int CELL_SIZE = 8;
	private FrameLayout frame;
	private int sizePerCell = 10;
	private int spacePerCell = 14;
	private int startX = 10,startY = 10;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
    	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN );
		super.onCreate(savedInstanceState);
		handler = new Handler();
		cells = new ImageView[CELL_SIZE][CELL_SIZE];
		setContentView(R.layout.play_table);
		frame = (FrameLayout) findViewById(R.id.play_table_frame);
		initScreen();
		initOption();
		startX = Const.getPositionCrosswordX();
		startY = Const.getPositionCrosswordY();
		sizePerCell = Const.getSizePerCell();
		spacePerCell = Const.getCellSpace();
		
		for(int i = 0 ; i < CELL_SIZE ; i++){
			for(int j = 0 ; j < CELL_SIZE ; j++){
				final ImageView imgView = new ImageView(this);
				FrameLayout.LayoutParams imgViewLp = new FrameLayout.LayoutParams(sizePerCell, sizePerCell);
				imgViewLp.topMargin = startY + i * sizePerCell + i * spacePerCell;
				imgViewLp.leftMargin = startX + j* sizePerCell + j * spacePerCell;
				imgViewLp.gravity = Gravity.TOP | Gravity.LEFT;
				imgView.setLayoutParams(imgViewLp);
				cells[i][j] = imgView;
				frame.addView(imgView);
				final int ii = i;
				final int jj = j;
				imgView.setOnClickListener(new View.OnClickListener() {
					
					public void onClick(View v) {
						// TODO Auto-generated method stub
						System.out.println("img view on touch");
						if(currentOption != null){
							
							onMove(ii,jj);
						} else {
							return;
						}
					}
				});
			}
		}
		frame.setBackgroundDrawable(new BitmapDrawable(ResourceManager.getInstance().getImage(this, "play/main.png")));
		
		// BTN BACK
		CustomButton btnBack = new CustomButton(this);
		btnBack.initResource(ResourceManager.getInstance().getImage(this, "play/back.png"));
		LayoutParams btnBackLayout = new LayoutParams(btnBack.getResourceWidth(), btnBack.getResourceHeight());
		Const.setPositionBtnBack(btnBackLayout);
		btnBackLayout.gravity = Gravity.TOP | Gravity.LEFT;
		btnBack.setLayoutParams(btnBackLayout);
		frame.addView(btnBack);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				finish();
			}
		});
		
		createLastestWord();
		createScore();
		createFriendOption();
		createYourOption();
		test();
	}
	
	private void initScreen(){
		currentYourOptionSize = Const.getSizeYourOptionWordWithoutSpace();
		Log.d(ACCOUNT_SERVICE, "" + currentYourOptionSize);
		currentMyOptionSize = Const.getSizeMyOptionWordWithoutSpace();
		Log.d(ACCOUNT_SERVICE, "" + currentMyOptionSize);
	}
	
	public void yourMove(char c,int x,int y){
		cells[y][x].setImageBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_YOUR_WORD, c));
	}
	private void onMove(int i,int j){
		// check
		char c = (Character)currentOption.getTag();
		cells[i][j].setImageBitmap(BitmapFont.getInstance(PlayActivity.this).getChar(BitmapFont.FONT_MY_WORD, c));
	
	}
	private void test(){
		setMyOption(new char[]{'A','B','C','D','E','F'});
		setYourOption(new char[]{'A','B','C','D','E','F'});
		setLastestWord(new char[]{'V', 'I', 'N', 'H'});
	}
	private ImageView[] currentYourOption, currentMyOption;
	private void initOption(){
		currentMyOption = new ImageView[6];
		currentYourOption = new ImageView[6];
		for(int i = 0 ; i < 6 ; i++){
			final int j = i;
			currentMyOption[i] = new ImageView(this);
			currentYourOption[i] = new ImageView(this);
			currentMyOption[i].setTag('a');
			currentYourOption[i].setTag('a');
			currentMyOption[i].setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					char c = (Character) currentMyOption[j].getTag();
					if(currentOption != null){
						System.out.println("my option not null");
						char c1 = (Character)currentOption.getTag();
						//currentOption.setImageBitmap(BitmapFont.getInstance(PlayActivity.this).getChar(BitmapFont.FONT_MY_WORD, c1));
						// @hungvjnh
						Bitmap temp = Bitmap.createScaledBitmap(BitmapFont.getInstance(PlayActivity.this).getChar(BitmapFont.FONT_MY_WORD, c1), currentMyOptionSize, currentMyOptionSize, false);
						currentOption.setImageBitmap(temp);
					}
					//currentMyOption[j].setImageBitmap(BitmapFont.getInstance(PlayActivity.this).getChar(BitmapFont.FONT_SELECTING_WORD, c));
					// @hungvjnh
					Bitmap temp = Bitmap.createScaledBitmap(BitmapFont.getInstance(PlayActivity.this).getChar(BitmapFont.FONT_SELECTING_WORD, c), currentMyOptionSize, currentMyOptionSize, false);
					currentMyOption[j].setImageBitmap(temp);
					
					currentOption = currentMyOption[j];
				}
			});
			//FrameLayout.LayoutParams myOptionLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
			// @hungvjnh
			FrameLayout.LayoutParams myOptionLp = new FrameLayout.LayoutParams(currentMyOptionSize, currentMyOptionSize);
			
			myOptionLp.gravity = Gravity.TOP | Gravity.LEFT;
			Const.setPositionMyOption(myOptionLp, i);
			currentMyOption[i].setLayoutParams(myOptionLp);
			
			//FrameLayout.LayoutParams yourOptionLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
			// @hungvjnh
			FrameLayout.LayoutParams yourOptionLp = new FrameLayout.LayoutParams(currentYourOptionSize, currentYourOptionSize);
			
			yourOptionLp.gravity = Gravity.TOP | Gravity.LEFT;
			Const.setPositionYourOption(yourOptionLp, i);
			currentYourOption[i].setLayoutParams(yourOptionLp);
			
			frame.addView(currentMyOption[i]);
			frame.addView(currentYourOption[i]);
		}
	}
	private ImageView currentOption = null;
	
	private int currentMyOptionSize = 38;
	private int currentYourOptionSize = 22;
	//api
	public void setYourOption(char[] option){
		for(int i = 0 ; i < option.length ; i++){
			//currentYourOption[i].setImageBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_YOUR_WORD, option[i]));
			// @hungvjnh
			Bitmap temp = Bitmap.createScaledBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_YOUR_WORD, option[i]), currentYourOptionSize, currentYourOptionSize, false);
			currentYourOption[i].setImageBitmap(temp);
			
			currentYourOption[i].setTag(option[i]);
		}
	}
	public void setMyOption(char[] option){
		for(int i = 0 ; i < option.length ; i++){
			//currentMyOption[i].setImageBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_MY_WORD, option[i]));
			// @hungvjnh
			Bitmap temp = Bitmap.createScaledBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_MY_WORD, option[i]), currentMyOptionSize, currentMyOptionSize, false);
			currentMyOption[i].setImageBitmap(temp);
			
			currentMyOption[i].setTag(option[i]);
			
		}
		
	}
	public void setLastestWord(char[] words){
		int offset = (int) Math.floor((8 - words.length)/2);
		for(int j = 0; j < offset; j++){
			lastestWord[j].setImageBitmap(null);
		}
		for(int i = 0 ; i < words.length ; i++){
			//currentMyOption[i].setImageBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_MY_WORD, option[i]));
			// @hungvjnh
			Bitmap temp = Bitmap.createScaledBitmap(BitmapFont.getInstance(this).getChar(BitmapFont.FONT_YOUR_WORD, words[i]), currentYourOptionSize, currentYourOptionSize, false);
			lastestWord[offset + i].setImageBitmap(temp);
			
			lastestWord[offset + i].setTag(words[i]);
			
		}
	}
//	private ImageView lastestWordImgView;
	private ImageView[] lastestWord;
	//init components
	private void createLastestWord(){
//		LinearLayout lastestWordParent = (LinearLayout) getLayoutInflater().inflate(R.layout.lastest_word, null);
//		FrameLayout.LayoutParams parentLp = new FrameLayout.LayoutParams(Const.getSizeLastestWord(),BitmapFont.getInstance(this).getAlphabeHeight());
//		lastestWordImgView = (ImageView) lastestWordParent.findViewById(R.id.lastest_word_img);
//		parentLp.gravity = Gravity.TOP | Gravity.LEFT;
//		Const.setPositionLastestWord(parentLp, Const.getSizeLastestWord(), BitmapFont.getInstance(this).getAlphabeHeight());
//		lastestWordParent.setLayoutParams(parentLp);
//		frame.addView(lastestWordParent);
		lastestWord = new ImageView[8];

		
		
		for(int i = 0 ; i < 8 ; i++){
			final int j = i;
			lastestWord[i] = new ImageView(this);
			lastestWord[i].setTag('a');
			
			//FrameLayout.LayoutParams yourOptionLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
			// @hungvjnh
			FrameLayout.LayoutParams lastestWordLp = new FrameLayout.LayoutParams(currentYourOptionSize, currentYourOptionSize);
			
			lastestWordLp.gravity = Gravity.TOP | Gravity.LEFT;
			Const.setPositionLastestWord(lastestWordLp, i);
			lastestWord[i].setLayoutParams(lastestWordLp);
			
			frame.addView(lastestWord[i]);
		}
	}
	private ImageView myScore,yourScore;
	private void createScore(){
		myScore = new ImageView(this);
		FrameLayout.LayoutParams myScoreLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
		myScoreLp.gravity = Gravity.TOP | Gravity.LEFT;
		Const.setPositionMyScore(myScoreLp);
		myScore.setLayoutParams(myScoreLp);
		
		yourScore = new ImageView(this);
		FrameLayout.LayoutParams yourScoreLp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
		yourScoreLp.gravity = Gravity.TOP | Gravity.LEFT;
		Const.setPositionYourScore(yourScoreLp);
		yourScore.setLayoutParams(yourScoreLp);
		
		frame.addView(myScore);
		frame.addView(yourScore);
	}
	private void createYourOption(){
//		FrameLayout parent = new FrameLayout(this);
//		FrameLayout.LayoutParams parentLp = new FrameLayout.LayoutParams(Const.getSizeMyOptionWord(),Const.getSizeMyOptionWord() / 6);
//		parentLp.gravity = Gravity.TOP | Gravity.LEFT;
//		Const.setPositionMyOption(parentLp);
//		parent.setLayoutParams(parentLp);
//		frame.addView(parent);
	}
	private void createFriendOption(){
//		FrameLayout parent = new FrameLayout(this);
//		FrameLayout.LayoutParams parentLp = new FrameLayout.LayoutParams(Const.getSizeYourOptionWord(),Const.getSizeYourOptionWord() / 6);
//		parentLp.gravity = Gravity.TOP | Gravity.LEFT;
//		Const.setPositionYourOption(parentLp);
//		parent.setLayoutParams(parentLp);
//		frame.addView(parent);
	}
	
	private static final int DURATION_TRANSLATE_ANIMATION = 500;
	private void swapAnimation(ImageView from,ImageView dest){
		// only support frame layout
		FrameLayout.LayoutParams fromLp = (LayoutParams) from.getLayoutParams();
		FrameLayout.LayoutParams destLp = (LayoutParams) from.getLayoutParams();
		startAnimation(from, 0, 0, destLp.leftMargin - fromLp.leftMargin, destLp.topMargin - fromLp.topMargin, DURATION_TRANSLATE_ANIMATION);
		startAnimation(dest, 0, 0, fromLp.leftMargin - destLp.leftMargin, fromLp.topMargin - fromLp.topMargin, DURATION_TRANSLATE_ANIMATION);
		handler.postDelayed(new Runnable() {
			
			public void run() {
				//TODO:swap image between from and dest
				
			}
		}, DURATION_TRANSLATE_ANIMATION);
	}
	private void startAnimation(View v,int xFrom,int yFrom,int xDest,int yDest,int duration){
		Animation a = new TranslateAnimation(xFrom,xDest,yFrom,yDest);
        a.setDuration(duration);
        v.startAnimation(a);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return super.onTouchEvent(event);
	}
	
	
	private boolean isWord(char c) {
		return (c >= 'A' && c <= 'Z'? true:false);
	}
	
	private char[]rowToArray(int x, int y){
		char []arr = new char[8];
		
		for(int i = 0; i < 8; i++) {
			arr[i] = (Character)cells[i][y].getTag();
		}
		
		return arr;
	}
	
	private char[]colToArray(int x, int y){
		char []arr = new char[8];
		
		for(int i = 0; i < 8; i++) {
			arr[i] = (Character)cells[x][i].getTag();
		}
		
		return arr;
	}
	
	private char[]dia_mainToArray(int x, int y){
		char arr[] = new char[8];
		int i, j;
		for(i = 0; i < 8; i++)
			arr[i] = 'a';
		i = x;
		j = y;
		while(i >= 0 && j >= 0) {
			arr[i] = (Character)cells[i][j].getTag();
			i--;
			j--;
		}
		i = x+1;
		j = y+1;
		while(i < 8 && j < 8) {
			arr[i] = (Character)cells[i][j].getTag();
			i++;
			j++;
		}
		
		return arr;
	}
	private char[]dia_subToArray(int x, int y){
		char arr[] = new char[8];
		int i, j;
		for(i = 0; i < 8; i++)
			arr[i] = 'a';
		i = x;
		j = y;
		while(i >= 0 && j < 8) {
			arr[i] = (Character)cells[i][j].getTag();
			i--;
			j++;
		}
		i = x+1;
		j = y-1;
		while(i < 8 && j >= 0) {
			arr[i] = (Character)cells[i][j].getTag();
			i++;
			j--;
		}
		
		return arr;
	}
	
	private Vector<String> listWordFromArr(int x, int y, char []arr){
		int xmin = x;
		int xmax = x;
		int i;
		int j;
		int k;
		char c;
		
		for(i = x; i >=0; i--) {
			if(!isWord(arr[i]) ) {
				xmin = i + 1;
			}
		}
		for(i = x; i < 8; i++) {
			if(!isWord(arr[i]) ) {
				xmax = i - 1;
			}
		}
		
		Vector<String> vector = new Vector<String>(10);
		
		for(i = xmin; i <= x; i++) {
			for(j = (xmin+3 > x? xmin:x); j <= xmax; j++) {
				String str1 = "";
				String str2 = "";
				for(k = i; k <= j; k++) {
					c = arr[k];
					str1 += c;
					str2 = c + str2;
				}
				vector.add(str1);
				vector.add(str2);
			}
		}
		
		return vector;
	}
	
	//get list of text by row
	
	private Vector<String> listWordByRow(int x, int y){
		char []arr = rowToArray(x, y);
		return listWordFromArr(x, y, arr);
	}
	
	//get list of text by col
	private Vector<String> listWordByCol(int x, int y){
		char []arr = colToArray(x, y);
		return listWordFromArr(x, y, arr);
	}
	
	//get list of text by top-left bottom-down
	private Vector<String> listWordByDia_main(int x, int y){
		char []arr = dia_mainToArray(x, y);
		return listWordFromArr(x, y, arr);
	}
	//get list of text by top-right bottom-left
	private Vector<String> listWordByDia_sub(int x, int y){
		char []arr = dia_subToArray(x, y);
		return listWordFromArr(x, y, arr);
	}
}
